package com.lwj.service.common;

import com.lwj.vo.administration.DepartmentTreeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

@Service
public class AsyncTaskExecutorServiceImpl implements AsyncTaskExecutorService{

    @Override
    public <T> List<T> callable(List<Callable<T> >task){
        //线程隔离，不用spring管理的线程池
        ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 10, 200, TimeUnit.MILLISECONDS,
                new ArrayBlockingQueue<Runnable>(5));
        List<T> result=new ArrayList<>();
        List<Future<T>> submitList=new ArrayList<>();
        for (int i = 0; i < task.size(); i++) {
            Future<T> submit = executor.submit(task.get(i));
            submitList.add(submit);
        }
        //由于get方法会导致线程阻塞，所以要在提交多线程任务后处理数据
        for(Future<T> future: submitList){
            //get方法是阻塞的，会等待所有线程执行完成后在取值
            try {
                T t = future.get();
                result.add(t);
            }catch (Exception e) {
                throw new RuntimeException(e);
            }

        }
        executor.shutdown();
        return result;
    }

    @Override
    public <T> List<T> callableList(List<Callable<List<T>>> task) {
        //线程隔离，不用spring管理的线程池
        ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 10, 200, TimeUnit.MILLISECONDS,
                new ArrayBlockingQueue<Runnable>(5));
        List<T> result=new ArrayList<>();
        List<Future<List<T>>> submitList=new ArrayList<>();
        for (int i = 0; i < task.size(); i++) {
            Future<List<T>> submit = executor.submit(task.get(i));
            submitList.add(submit);
        }
        //由于get方法会导致线程阻塞，所以要在提交多线程任务后处理数据
        for(Future<List<T>> future: submitList){
            //get方法是阻塞的，会等待所有线程执行完成后在取值
            try {
                List<T> t = future.get();
                result.addAll(t);
            }catch (Exception e) {
                throw new RuntimeException(e);
            }

        }
        executor.shutdown();
        return result;
    }
}
